package com.mewpipe.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mewpipe.crypt.BCrypt;
import com.mewpipe.dao.DaoFactory;
import com.mewpipe.dao.UserDao;
import com.mewpipe.entity.User;
import com.mewpipe.entity.UserSession;

/**
 * Servlet implementation class LogUserServlet
 */
@WebServlet("/login")
public class LogUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	private UserDao userdao;

	@Override
	public void init() throws ServletException {
		
		userdao = DaoFactory.getInstance().getUserDao();
		
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String pseudo = request.getParameter("pseudo");
		String password = request.getParameter("password");
		
		
		User userfind = userdao.getUserByName(pseudo);
		boolean err = false;
		if(userfind!=null){
			
			if(BCrypt.checkpw(password, userfind.getPassword())){
				
				UserSession usersession = new UserSession(userfind.getId(), userfind.getPseudo(), userfind.getTypeAcc());
				HttpSession session = request.getSession();
				session.setAttribute("UserSession", usersession);
				
				//request.getRequestDispatcher("/Index").forward(request, response);
				//response.sendRedirect(request.getServletContext().getContextPath()+"/GetUserInfo?id="+usersession.getId());
				response.sendRedirect(request.getServletContext().getContextPath()+"/Index");
			}
			
			else {
				
				request.setAttribute("errorPassword", false);
				err = true;
				
				
			}
			
			
		}
		
		else {
			err = true;
			request.setAttribute("errorLogin", false);
			
		}
		if (err){
			response.sendRedirect(request.getServletContext().getContextPath()+"/Login.jsp");
		//request.getRequestDispatcher("/Login.jsp").forward(request, response);
		}
		
		
	}

}
